package com.hexanet.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;

import com.hexanet.bom.Player;
import com.hexanet.client.writer.HexanetWriter;

import flexjson.JSONDeserializer;
import flexjson.JSONSerializer;

public class PlayerResourceClient {

    public void loginPlayer() throws Exception
    {
	Player p = new Player();
	p.setMail("stefanstift@gmail.com");
	p.setPasswordSha1("test");
	
	DefaultHttpClient httpclient = new DefaultHttpClient();
	
	httpclient.getCredentialsProvider()
	.setCredentials(
		new AuthScope("localhost", 8443),
		new UsernamePasswordCredentials(
			p.getMail(), p.getPasswordSha1()));
	
	HexanetWriter writer = new HexanetWriter();
	HttpPost postRequest = writer.getPostRequest(ClientUtil.serverUrl
		+ ClientUtil.resPath + "/players/login", httpclient, p);
	
	
	HttpResponse response = null;
	response = httpclient.execute(postRequest);

	StatusLine line = response.getStatusLine();
	System.out.println(line.getStatusCode() + " - "
		+ line.getReasonPhrase());

	// return code indicates upload failed so throw exception
	if (line.getStatusCode() < 200 || line.getStatusCode() >= 300) {
	    throw new Exception("POST failed");
	}
	
	BufferedReader br = new BufferedReader(new InputStreamReader(
		(response.getEntity().getContent())));

	String json = br.readLine();

	JSONDeserializer<Player> jsonDeserialzier = new JSONDeserializer<Player>();
	Player loginPlayer = jsonDeserialzier.deserialize(json);
	
	System.out.println("client size = " + loginPlayer.getOwningCells().size());

	System.out.println(loginPlayer.getNickname());
	System.out.println(loginPlayer.getMail());
	//System.out.println(loginPlayer.getOwningCells().get(0).getName());


	httpclient.getConnectionManager().shutdown();
    }
   
    
    
    public void getPlayerById() throws IOException, KeyManagementException, NoSuchAlgorithmException {

	DefaultHttpClient httpclient = new DefaultHttpClient();
	
	HttpGet getRequest = new HttpGet(ClientUtil.serverUrl
		+ ClientUtil.resPath + "/players/5");
	
	getRequest.addHeader("accept", "application/json");

	httpclient.getCredentialsProvider()
		.setCredentials(
			new AuthScope("localhost", 8443),
			new UsernamePasswordCredentials(
				"stefanstift@gmail.com", "test"));

	HttpResponse response = httpclient.execute(getRequest);

	if (response.getStatusLine().getStatusCode() != 200) {
	    throw new RuntimeException("Failed : HTTP error code : "
		    + response.getStatusLine().getStatusCode());
	} 
	
	StatusLine line = response.getStatusLine();
	System.out.println(line.getStatusCode() + " - "
		+ line.getReasonPhrase());

	BufferedReader br = new BufferedReader(new InputStreamReader(
		(response.getEntity().getContent())));

	String json = br.readLine();

	JSONDeserializer<Player> jsonDeserialzier = new JSONDeserializer<Player>();
	Player p = jsonDeserialzier.deserialize(json);

	System.out.println(p.getNickname());
	System.out.println(p.getMail());
	//System.out.println(p.getOwningCells().get(0).getName());

	httpclient.getConnectionManager().shutdown();

    }

    public void addPlayer() throws Exception {

	Player p = new Player();
	p.setNickname("Player4");
	p.setMail("player4@gmx.at");
	p.setPasswordSha1("test");
	p.setPasswordSha1Repeat("test");

	DefaultHttpClient httpclient = new DefaultHttpClient();
	
	// use default creidentials for registering a new user - only a client that knows
	// the default cridentials can do this - its a feature! :D
	httpclient.getCredentialsProvider()
	.setCredentials(
		new AuthScope("localhost", 8443),
		new UsernamePasswordCredentials(
			"admin@hexanet.com", "admin"));
	
	
	HexanetWriter writer = new HexanetWriter();
	HttpPut putRequest = writer.getPutRequest(ClientUtil.serverUrl
		+ ClientUtil.resPath + "/players/create", httpclient, p);
	

	HttpResponse response = null;
	response = httpclient.execute(putRequest);

	StatusLine line = response.getStatusLine();
	System.out.println(line.getStatusCode() + " - "
		+ line.getReasonPhrase());

	// return code indicates upload failed so throw exception
	if (line.getStatusCode() < 200 || line.getStatusCode() >= 300) {
	    throw new Exception("PUT failed");
	}

	httpclient.getConnectionManager().shutdown();
    }
    
    public void savePlayer() throws Exception {

	Player p = new Player();
	p.setId(5L);
	p.setNickname("Player4_change");
	p.setMail("player4@gmx.at");
	p.setPasswordSha1("a94a8fe5ccb19ba61c4c0873d391e987982fbbd3");
	p.setRank(null);

	DefaultHttpClient httpclient = new DefaultHttpClient();
	
	// use default creidentials for registering a new user - only a client that knows
	// the default cridentials can do this - its a feature! :D
	httpclient.getCredentialsProvider()
	.setCredentials(
		new AuthScope("localhost", 8443),
		new UsernamePasswordCredentials(
			"player4@gmx.at", "test"));
	
	
	HexanetWriter writer = new HexanetWriter();
	HttpPut putRequest = writer.getPutRequest(ClientUtil.serverUrl
		+ ClientUtil.resPath + "/players/save", httpclient, p);
	

	HttpResponse response = null;
	response = httpclient.execute(putRequest);

	StatusLine line = response.getStatusLine();
	System.out.println(line.getStatusCode() + " - "
		+ line.getReasonPhrase());

	// return code indicates upload failed so throw exception
	if (line.getStatusCode() < 200 || line.getStatusCode() >= 300) {
	    throw new Exception("PUT failed");
	}

	httpclient.getConnectionManager().shutdown();
    }
    
    public void removePlayer() throws Exception {

	DefaultHttpClient httpclient = new DefaultHttpClient();
	
	// use default creidentials for registering a new user - only a client that knows
	// the default cridentials can do this - its a feature! :D
	httpclient.getCredentialsProvider()
	.setCredentials(
		new AuthScope("localhost", 8443),
		new UsernamePasswordCredentials(
			"stefanstift@gmail.com", "test"));
	
	HttpDelete deleteRequest = new HttpDelete(ClientUtil.serverUrl
		+ ClientUtil.resPath + "/players/remove/5");

	HttpResponse response = null;
	response = httpclient.execute(deleteRequest);

	StatusLine line = response.getStatusLine();
	System.out.println(line.getStatusCode() + " - "
		+ line.getReasonPhrase());

	// return code indicates upload failed so throw exception
	if (line.getStatusCode() < 200 || line.getStatusCode() >= 300) {
	    throw new Exception("PUT failed");
	}

	httpclient.getConnectionManager().shutdown();
    }
    
    
    
    
    
}
